package com.ty.store.service.impl;

import com.ty.store.entity.User;
import com.ty.store.mapper.UserMapper;
import com.ty.store.service.IUserService;
import com.ty.store.service.ex.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.UUID;

/**
 * @author ty
 */
@Service
public class UserServiceImpl implements IUserService {
    @Autowired
    private UserMapper userMapper;
    @Override
    public void reg(User user) {
        String username = user.getUsername();
        User result = userMapper.findUsername(username);
        if (result != null){
            throw new UsernameDuplicatedException("用户名被占用");
        }
        Date date = new Date();
        // 补全数据：加密后的密码
        String oldPassword = user.getPassword();
        String salt = UUID.randomUUID().toString().toUpperCase();
        user.setSalt(salt);
        String md5Password = getMD5Password(oldPassword,salt);
        user.setPassword(md5Password);
        user.setIsDelete(0);
        user.setCreatedTime(date);
        user.setModifiedTime(date);
        user.setCreatedUser(user.getUsername());
        user.setModifiedUser(user.getUsername());
        Integer insert = userMapper.insert(user);
        if (insert != 1){
            throw new InsertException("注册中的未知异常");
        }
    }

    @Override
    public User login(String username, String password) {
        User username1 = userMapper.findUsername(username);
        if (username1 == null){
            throw new UserNotFoundException("用户不存在");
        }
        String salt = username1.getSalt();
        String newpassword = getMD5Password(password,salt);
        String oldpassword = username1.getPassword();
        if (!newpassword.equals(oldpassword)){
            throw new PasswordNotMatchException("密码不正确");
        }
        if (username1.getIsDelete() == 1){
            throw new UserNotFoundException("用户不存在");
        }
        User user = new User();
        user.setUsername(username1.getUsername());
        user.setUid(username1.getUid());
        user.setAvatar(username1.getAvatar());
        return user;
    }

    @Override
    public void changePassword(Integer uid, String username, String oldPassword, String newPassword) {
        User result = userMapper.findUserById(uid);
        if (result == null || result.getIsDelete() == 1){
            throw new UserNotFoundException("用户不存在");
        }
        String oldMd5Password = getMD5Password(oldPassword, result.getSalt());
        if (!oldMd5Password.equals(result.getPassword())){
            throw new PasswordNotMatchException("密码错误");
        }
        String newMd5Password = getMD5Password(newPassword, result.getSalt());
        Integer rows = userMapper.updateById(uid, newMd5Password, username, new Date());
        if (rows != 1){
            throw new UpdateException("更新数据未知异常");
        }
    }

    @Override
    public void changeById(Integer uid, String username, User user) {
        User result = userMapper.findUserById(uid);
        // 判断查询结果是否为null
        if (result == null) {
            // 是：抛出UserNotFoundException异常
            throw new UserNotFoundException("用户数据不存在");
        }

        // 判断查询结果中的isDelete是否为1
        if (result.getIsDelete().equals(1)) {
            // 是：抛出UserNotFoundException异常
            throw new UserNotFoundException("用户数据不存在");
        }

        // 向参数user中补全数据：uid
        user.setUid(uid);
        // 向参数user中补全数据：modifiedUser(username)
        user.setModifiedUser(username);
        // 向参数user中补全数据：modifiedTime(new Date())
        user.setModifiedTime(new Date());
        // 调用userMapper的updateInfoByUid(User user)方法执行修改，并获取返回值
        Integer rows = userMapper.updateByUid(user);
        // 判断以上返回的受影响行数是否不为1
        if (rows != 1) {
            // 是：抛出UpdateException异常
            throw new UpdateException("更新用户数据时出现未知错误，请联系系统管理员");
        }
    }

    @Override
    public User getByUid(Integer uid) {
        User result = userMapper.findUserById(uid);
        if (result == null ||result.getIsDelete() == 1){
            throw new UserNotFoundException("用户不存在");
        }
        User user = new User();
        user.setUsername(result.getUsername());
        user.setPhone(result.getPhone());
        user.setEmail(result.getEmail());
        user.setGender(result.getGender());
        return user;
    }

    @Override
    public void changeAvatar(Integer uid, String avatar, String username) {
        User result = userMapper.findUserById(uid);
        if (result == null ||result.getIsDelete() == 1){
            throw new UserNotFoundException("用户不存在");
        }
        Integer rows = userMapper.updateAvatarByUid(uid, avatar, username, new Date());
        if (rows != 1){
            throw new UpdateException("更新时异常");
        }

    }

    private String getMD5Password(String password,String salt){
        for (int i = 0; i < 3; i++) {
            password = DigestUtils.md5DigestAsHex((salt + password + salt).getBytes()).toUpperCase();
        }
        return password;
    }
}
